const { qiniu } = require('../config/config');
const { startProcess, qiniuUpload } = require('../libs/utils'),
      { addSliderData } = require('../services/Slider'),
      { addAgencyInfo } = require('../services/AgencyInfo'),
      { addRecomCourse } = require('../services/RecomCourse'),
      { addCollection } = require('../services/Collection'),
      { addTeacher } = require('../services/Teacher'),
      { addStudent } = require('../services/Student'),
      { addCourseTab } = require('../services/CourseTab'),
      { addCourse } = require('../services/Course'),
      { addAboutus } = require('../services/AboutUs'),
      { CRAWLER } = require('../config/error_config'),
      { returnInfo } = require('../libs/utils'),
      config = require('../config/config');

class Crawler {
    async crawlAction(ctx, next) {
        const { apiName } = ctx.request.body;
  
        // 此处的this已经改变 不能使用this[field]调用方法
        // 爬取对应field数据
        const res = await Crawler.prototype[apiName]();

        ctx.body = res;
    }

    // 轮播图数据
    async crawlSliderData(){ 
        return new Promise((resolve, reject) => {
            startProcess({ // 开启子进程
                file: 'slider', // 子进程执行的代码路径
                async message(data){ 
                    data.map(async item => {
                        // 判断存在图片地址， 并且图片名为空 还未修改
                        if(item.imgUrl && !item.imgKey){
                            const qiniu = config.qiniu;
                            try{ // 网络资源可能报错使用try
                                const imgData = await qiniuUpload({
                                    url: item.imgUrl,
                                    bucket: qiniu.bucket.tximg.bucket_name,
                                    ext: '.jpg', // 文件后缀
                                });
                                // console.log(imgData);
                                // 上传结果返回的是文件名， 文件名存在的话返回成功，重新赋值到data中
                                console.log(imgData.key);
                                if(imgData.key){
                                    item.imgKey = imgData.key;
                                }
                                // 将数据添加到数据库中
                                const result = await addSliderData(item);
                                if(result){
                                    console.log('data create Ok');
                                }else{
                                    console.log('fail data');
                                }
                            }catch(e){
                                console.log(e);
                            }
                            
                        }
                    });
                    console.log(data);
                    // 数据爬取成功
                    resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
                },
                async exit(code){
                    console.log(code);
                },
                async error(error){
                    console.log(error);
                    // 数据爬取失败
                    resolve(returnInfo(CRAWLER.CRAWL_FAILED));
                }
            })
        })
    }

    // 课程信息
    async crawlAgencyInfo(){
        return new Promise((resolve, reject) => {
            // 开启子进程
            startProcess({
                file: 'agencyInfo.js',
                async message(data){ // 获取页面爬取的数据
                    if(data.logoUrl && !data.logoKey){
                        // 上传网络资源需要加try
                        try{
                            const qiniu = config.qiniu;
                            // 上传七牛云将logo
                            const logoData = await qiniuUpload({
                                url: data.logoUrl, // 图片网络资源地址
                                bucket: qiniu.bucket.tximg.bucket_name, // 七牛上的空间名
                                ext: '.jpg' // 图片后缀
                            });

                            // 上传成功后返回的是图片的名字
                            if(logoData.key){
                                data.logoKey = logoData.key;
                            }
                            console.log(data);
                            // 新增数据
                            const res = await addAgencyInfo(data);
                            console.log(res);
                            if(res){
                                console.log('机构信息添加成功！');
                            } else {
                                console.log('机构信息添加失败！！！');
                            }
                        } catch(e){
                            console.log(e);
                        }
                    }
                    // 数据爬取成功
                    resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
                }, 
                async exit(code){
                    console.log(code);
                },
                async error(error){
                    console.log(error);
                    // 数据爬取失败
                    resolve(returnInfo(CRAWLER.CRAWL_FAILED));
                }
            })
        })
    }

    // 关于我们
    async crawlAboutUs(){
        return new Promise((resolve, reject) => {
            startProcess({
                file: 'aboutus',
                async message(data){  
                    try{
                        if(data.posterUrl && !data.posterImgKey){
                            const qiniu = config.qiniu;
    
                            const imageData = await qiniuUpload({
                                url: data.posterUrl,
                                bucket: qiniu.bucket.tximg.bucket_name,
                                ext: '.jpg'
                            });
    
                            if(imageData.key){
                                data.posterImgKey = imageData.key;
                            }
                            console.log(data);
                            const res = await addAboutus(data);
                            
                            if(res){
                                console.log('添加关于我们成功');
                            } else {
                                console.log('添加关于我们失败');
                            }
                        }
                    } catch(e){
    
                    }
                    // 数据爬取成功
                    resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
                },
                async exit(code){
                    console.log(code);
                },
                async error(err){
                    console.log(err);
                    // 数据爬取失败
                    resolve(returnInfo(CRAWLER.CRAWL_FAILED));
                }
            })
        })
    }

    // 推荐课程
    async crawlRecomCourse(){
        return new Promise((resolve, reject) => {
            // 开启子进程
            startProcess({
                file: 'recomCourse.js', // 执行子进程的文件
                async message(data){
                    console.log(data);
                    // 遍历数组data
                    data.map(async item => {
                        try{
                            // 上传课程图片
                            if(item.posterUrl && !item.posterKey){
                                const posterData = await qiniuUpload({
                                    url: item.posterUrl,
                                    bucket: qiniu.bucket.tximg.bucket_name,
                                    ext: '.jpg'
                                });

                                if(posterData.key){
                                    item.posterKey = posterData.key;
                                }
                            }

                            // 上传老师图片
                            if(item.teacherImg && !item.teacherImgKey){
                                const teacherImgData = await qiniuUpload({
                                    url: item.teacherImg,
                                    bucket: qiniu.bucket.tximg.bucket_name,
                                    ext: '.jpg'
                                });

                                if(teacherImgData.key){
                                    item.teacherImgKey = teacherImgData.key;
                                }
                            }

                    
                            const res = await addRecomCourse(item);
                        
                            if(res){
                                console.log('添加课程信息成功!');
                            } else {
                                console.log('添加课程失败！！！');
                            }

                        } catch(e){

                        }
                    })
                    // 数据爬取成功
                    resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
                },
                async exit(code){
                    console.log(code);
                }, 
                async error(error){
                    console.log(error);
                    // 数据爬取失败
                    resolve(returnInfo(CRAWLER.CRAWL_FAILED));
                }
            })
        })
    }

    // 课程管理
    async crawlCollection(){
        return new Promise((resolve, reject) => {
            // 开启子进程
            startProcess({
                file: 'collection.js',
                async message(data){
                    // console.log(data);
                    // 遍历数据 上传七牛 保存数据库
                    data.map(async item => {
                        // 存在posterUrl 不存在posterKey
                        if(!item.posterKey && item.posterUrl){
                            const qiniu = config.qiniu;

                            // 上传七牛要try
                            try{
                                const imageData = await qiniuUpload({
                                    url: item.posterUrl,
                                    bucket: qiniu.bucket.tximg.bucket_name,
                                    ext: '.jpg'
                                });

                                console.log(imageData.key);
                                if(imageData.key){
                                    item.posterKey = imageData.key;
                                }
                                console.log(item);
                                // 入库
                                const res = await addCollection(item);

                                if(res){
                                    console.log('课程数据添加成功');
                                } else {
                                    console.log('课程数据添加失败!!!');
                                }
                            } catch(err){
                                console.log(err);
                            }
                        }
                    });
                    // 数据爬取成功
                    resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
                },
                async exit(code){
                    console.log(code);
                },
                async error(err){
                    console.log(err);
                    // 数据爬取失败
                    resolve(returnInfo(CRAWLER.CRAWL_FAILED));
                }
            })
        })
    }

    // 老师信息
    async crawlTeacher(){
        return new Promise((resolve, reject) => {
            startProcess({
                file: 'teacher.js',
                async message(data){
                    data.map(async item => {
                        if(item.teacherImg && !item.teacherImgKey){
                            console.log(item);
                            const qiniu = config.qiniu;
    
                            // 上传图片到七牛
                            const imgData = await qiniuUpload({
                                url: item.teacherImg,
                                bucket: qiniu.bucket.tximg.bucket_name,
                                ext: '.jpg'
                            });
    
                            if(imgData.key){
                                item.teacherImgKey = imgData.key;
                            }
    
                            const res = await addTeacher(item);
                            
                            if(res){
                                console.log('老师信息数据成功添加成功');
                            } else {
                                console.log('老师信息数据添加失败！');
                            }
                        }
                    })
                    // 数据爬取成功
                    resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
                },
                async exit(code){
                    console.log(code);
                },
                async error(error){
                    console.log(error);
                    // 数据爬取失败
                    resolve(returnInfo(CRAWLER.CRAWL_FAILED));
                }
            })
        })
    }

    // 学生信息
    async crawlStudent(){
        return new Promise((resolve, reject) => {
            startProcess({
                file: 'student',
                async message(data){
                    data.map(async item => {
                        if(item.studentImg && !item.studentImgKey){
                            try{
                                const qiniu = config.qiniu;
        
                                const imageData = await qiniuUpload({
                                    url: item.studentImg,
                                    bucket: qiniu.bucket.tximg.bucket_name,
                                    ext: '.jpg'
                                });
    
                                if(imageData.key){
                                    item.studentImgKey = imageData.key;
                                }
    
                                // 保存数据库
                                const res = await addStudent(item);
    
                                if(res){
                                    console.log('学生信息添加成功');
                                } else {
                                    console.log('学生信息添加失败！！！');
                                }
                                console.log(item);
                            }catch(e){
                                console.log(e);
                            }
                        }
                    })
                    // 数据爬取成功
                    resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
                },
                async exit(code){
                    console.log(code);
                },
                async error(err){
                    console.log(err);
                    // 数据爬取失败
                    resolve(returnInfo(CRAWLER.CRAWL_FAILED));
                }
            })
        })
    }

    // 课程分类
    async crawlCourseTab(){
        return new Promise((resolve, reject) => {
            startProcess({
                file: 'courseTab.js',
                async message(data){
                    data.map(async item => {
                        console.log(item);
                        const res = await addCourseTab(item);
    
                        if(res){
                            console.log('课程tab添加成功');
                        } else {
                            console.log('课程tab添加失败！！！');
                        }
                    })
                    // 数据爬取成功
                    resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
                },
                async exit(code){
                    console.log(code);
                },
                async error(err){
                    console.log(err);
                    // 数据爬取失败
                    resolve(returnInfo(CRAWLER.CRAWL_FAILED));
                }
            })
        })
    }

    // 课程信息
    async crawlCourseData(){
        return new Promise((resolve, reject) => {
            // 执行子进程
            startProcess({
                file: 'course.js',
                async message(data){
                    data.map(async item => {
                        if(item.posterUrl && !item.posterKey){
                            const qiniu = config.qiniu;

                            const imageData = await qiniuUpload({
                                url: item.posterUrl,
                                bucket: qiniu.bucket.tximg.bucket_name,
                                ext: '.jpg'
                            });

                            if(imageData.key){
                                item.posterKey = imageData.key;
                            }

                            const res = await addCourse(item);
                            if(res){
                                console.log('添加课程信息成功');
                            } else {
                                console.log('添加课程失败！！！');
                            }
                            console.log(item);
                        }
                    })
                    // 数据爬取成功
                    resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
                },
                async exit(code){
                    console.log(code);
                },
                async error(err){
                    console.log(err);
                    // 数据爬取失败
                    resolve(returnInfo(CRAWLER.CRAWL_FAILED));
                }
            })
        })
    }
}

module.exports = new Crawler();